package one.chapter_3;

import java.util.Iterator;

/**
 * 无序链表中的顺序查找
 * @param <Key>
 * @param <Value>
 */
public class SequentialSearchST<Key,Value> implements ST<Key,Value>{

    private Node head;
    private class Node{
         Key key;
         Value value;
         Node next;

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
    private int N;
    public SequentialSearchST(){

    }
    public void put(Key key, Value value) {
        if (key==null || value==null){
            //throw IllegalArgumentException("key or value cann't be null ");
        }

        //检查有无重复元素
        for (Node node=head;node!=null;node=node.next){
            if (key.equals(node.key)){
                node.value=value;//更新value
                return;
            }
        }
        N++;
        head=new Node(key,value,head);

    }

    public Value get(Key key) {
        for (Node node=head;node!=null;node=node.next){
            if (node.key.equals(key)){
                return node.value;
            }
        }

        return null;
    }

    public void delete(Key key) {
        for (Node node=head;node!=null;node=node.next){
            if (node.key.equals(key)){
                node.value=null;
                N--;
                break;
            }
        }


    }

    public Iterable<Key> keys() {
        return null;
    }

    public boolean contains(Key key) {
        return get(key)!=null;
    }

    public boolean isEmpty() {
        return size()==0;
    }

    public int size() {
        return N;
    }

    private class Iter implements Iterable<Key>{

        @Override
        public Iterator<Key> iterator() {
            return null;
        }
    }
}
